package com.auto.base.util;


import com.alibaba.fastjson.JSON;

import com.auto.base.model.DubboItem;
import com.auto.base.params.BaseAutoConfig;
import io.qameta.allure.Step;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.service.GenericService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DubboTemplate{
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private final ApplicationConfig applicationConfig = new ApplicationConfig();
    // 注册中心配置
    private final RegistryConfig registryConfig = new RegistryConfig();
    public DubboTemplate(BaseAutoConfig autoConfig) {
        applicationConfig.setName("autoTestService");
        registryConfig.setAddress(autoConfig.getDubboRegistryAddress());
        registryConfig.setGroup(autoConfig.getDubboRegistryGroup());
        registryConfig.setTimeout(10000);
    }

    @Step("发起dubbo请求")
    public Object sendMessage(DubboItem dubboItem) {
        log.info("request Dubbo Info is {}", dubboItem);
        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setRegistry(registryConfig);
        reference.setApplication(applicationConfig);
        reference.setProtocol("dubbo");
        reference.setGeneric(true);
        reference.setInterface(dubboItem.getInterfaceName());
        GenericService genericService = reference.get();
        Object invoke;
        try {
            invoke = genericService.$invoke(dubboItem.getMethod(), new String[]{dubboItem.getReqType().getName()}, new Object[]{JSON.parseObject(dubboItem.getJsonMessage())});
        } catch (Exception e) {
            log.error("invoke fail", e);
            throw e;
        }
        log.info("response message is {}", JSON.toJSONString(invoke));
        return invoke;
    }

    @Step("发起dubbo请求")
    public Object sendMessage(Class<?> itf, String method, Class<?> reqType, String reqMessage) {
        DubboItem dubboItem = DubboItem.builder().interfaceName(itf).method(method).reqType(reqType).jsonMessage(reqMessage).build();
        return sendMessage(dubboItem);
    }

    @Step("发起dubbo请求")
    public ReferenceConfig<GenericService> getReference(Class<?> c) {
        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setRegistry(registryConfig);
        reference.setApplication(applicationConfig);
        reference.setProtocol("dubbo");
        reference.setInterface(c);
        return reference;
    }
    /*public Object sendMessage(String methodName, String paramTypes, String jsonMessage) {
        return (Object) genericService.$invoke(methodName, new String[]{paramTypes}, new Object[]{JSON.parseObject(jsonMessage)});
    }*/
}
